import PropTypes from 'prop-types'
import React, { memo, useEffect, useState, useRef } from 'react'
import { message, Empty, Spin, Tooltip } from 'antd'

import VideoComponent from '@/components/video'
import { PreviewVideoWarpper } from './style'
import { getCameraList, getCameraUrl } from '@/api'
import { isArrayWithLength } from '@/utils'

const index = memo((props) => {
    const { builderLicenceNum } = props

    const [cameraList, setCameraList] = useState([])
    const [playUrl, setPlayUrl] = useState('')
    const [loading, setLoading] = useState(false)

    const onlineStatus = {
        0: { color: 'red', text: '离线' },
        1: { color: 'green', text: '在线' },
    }

    async function fetchCameraList() {
        setLoading(true)
        try {
            const res = await getCameraList({ builderLicenceNum })
            setCameraList(res.data.data)
        } catch (error) {
            message.error(error || "系统出错")
        } finally {
            setLoading(false)
        }
    }
    async function doubleClickCameraHandle(cameraInfo) {
        if (cameraInfo.status === 0) {
            message.warning("摄像头离线，无法查看视频")
            return
        }
        try {
            const res = await getCameraUrl({ cameraIndexCode: cameraInfo.cameraIndexCode })
            setPlayUrl(res.data.data.url)
        } catch (error) {
            message.error(error || "系统出错")
        }
    }
    const elRef = useRef()
    const el1Ref = useRef()
    useEffect(() => {
        builderLicenceNum && fetchCameraList()
    }, [builderLicenceNum])

    return (
        <PreviewVideoWarpper>
            <div className="preview-left">
                <Spin tip="数据加载中 ..." spinning={loading}>
                    <div className="list-warpper">
                        {isArrayWithLength(cameraList) && cameraList?.map((item, index) => {
                            return (
                                <div key={index} className='item-container' onDoubleClick={e => doubleClickCameraHandle(item)}>
                                    <div className='item-online-state' style={{ background: onlineStatus[item.status].color }}></div>
                                    <div className='item-content' ref={elRef}>
                                        <Tooltip title={item.name} >
                                            <div ref={el1Ref}>{item.name}</div>
                                        </Tooltip>
                                    </div>
                                </div>
                            )
                        })}
                        {!isArrayWithLength(cameraList) && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    </div>
                </Spin>
            </div>
            <div className="preview-right">
                <VideoComponent playUrl={playUrl} />
            </div>
        </PreviewVideoWarpper>
    )
})

index.propTypes = {}

export default index